{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f7b08241",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1.   -1.  ]\n",
      " [-1.    1.33]]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from numpy import random as nr\n",
    "np.set_printoptions(precision=2)\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "#各取500个标准正态分布的数据 \n",
    "x1=np.random.normal(0,1,500)\n",
    "x2=np.random.normal(0,1,500)\n",
    "\n",
    "#将x1，x2以向量的形式排列起来 \n",
    "X=np.vstack((x1,x2)).T\n",
    "\n",
    "\n",
    "#计算协方差\n",
    "def cov(x1,x2):\n",
    "    x1mean,x2mean=x1.mean(),x2.mean()\n",
    "    Sigma=np.sum((x1-x1mean)*(x2-x2mean))/(len(x1)-1)\n",
    "    return Sigma\n",
    "\n",
    "#协方差矩阵 \n",
    "def covMatrix(X):\n",
    "    matrix=np.array([[cov(X[0],X[0]),cov(X[0],X[1])],[cov(X[1],X[0]),cov(X[1],X[1])]])\n",
    "    return matrix\n",
    "\n",
    "covMatrix(X)\n",
    "\n",
    "\n",
    "### 解法2\n",
    "a = np.array([[1,2,3],[3,1,1]])\n",
    "print(np.cov(a))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60ca4ae0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
